package com.cn.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.cn.gmall.common.execption.GmallException;
import com.cn.gmall.common.result.Result;
import com.cn.gmall.model.enums.PaymentStatus;
import com.cn.gmall.model.enums.PaymentType;
import com.cn.gmall.model.order.OrderInfo;
import com.cn.gmall.model.payment.PaymentInfo;
import com.cn.gmall.order.client.OrderFeignClient;
import com.cn.gmall.payment.config.AliPayClientConfig;
import com.cn.gmall.payment.service.AlipayService;
import com.cn.gmall.payment.service.PaymentInfoService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.security.cert.TrustAnchor;


@Service
public class AlipayServiceImpl implements AlipayService {
    @Resource
    OrderFeignClient orderFeignClient;
    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayClient alipayClient;

    /**
     * 给支付宝发请求--->关闭支付支付记录
     * @param orderId
     * @return
     */
    @SneakyThrows
    @Override
    public Boolean closePay(Long orderId) {
//        交易号--->先拿到订单对象
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();
//        非空校验
        if (!ObjectUtils.isEmpty(orderInfo)){
            return  false;
        }
//-------------------------官方文档提供--->修改提交的参数----------------
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用支付宝关闭支付接口-->成功!");
            return true;
        } else {
            System.out.println("调用支付宝关闭支付接口-->失败!!");
//            人工处理
            return false;
        }
    }

    /***
     *给支付宝发请求---> 查询支付支付记录
     * @param orderId
     * @return
     */
    @SneakyThrows
    @Override
    public Boolean checkPayment(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();
//       非空验证
        if (ObjectUtils.isEmpty(orderInfo)){
            return  false;
        }
//----------------------------官方文档-->发送查询记录请求-----------------------

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "  \"out_trade_no\":\""+orderInfo.getOutTradeNo()+"\"," +
//                "  \"trade_no\":\"2014112611001004680 073956707\"," +
                "  \"query_options\":[" +
                "    \"trade_settle_info\"" +
                "  ]" +
                "}");

        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用支付宝查询记录-->成功!");
            return true;
        } else {
            System.out.println("调用支付宝查询记录-->失败!!");
            return false;
        }
    }

    /***
     * 退款
     * @param orderId
     * @return
     */

    @SneakyThrows
    @Override
    public boolean refund(Long orderId) {

//     配置类里面已经初始化了   AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                "app_id",
//                "your private_key",
//                "json",
//                "GBK",
//                "alipay_public_key",
//                "RSA2");

        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();
        if (ObjectUtils.isEmpty(orderInfo)) {
            return false;
        }

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            String fundChange = response.getFundChange();

            if ("Y".equals(fundChange)) {
                System.out.println("调用成功,退款成功");
//                关闭订单支付记录状态
                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                int i = paymentInfoService.updateOrderStatus(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name(), paymentInfo);
                if (i > 0) {
                    return true;
                }

            } else {

                System.out.println("退款失败");
            }

        } else {
            System.out.println("调用失败");

        }
        return false;
    }

    /**
     * 发起支付宝支付
     *
     * @param orderId
     * @return
     */
    @Override
    public String createAliPay(Long orderId) {

//        获取当前订单
//        Result<OrderInfo> orderInfo = orderFeignClient.getOrderInfo(orderId);

        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();

        if (orderInfo != null && !"UNPAID".equals(orderInfo.getOrderStatus())) {
            throw new GmallException("订单已关闭 或已支付", 201);
        }
//        保存记录
        paymentInfoService.savePaymentInfo(orderInfo);

//        对接支付宝


//          创建API对应的request
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

/***异步接收地址，仅支持http/https，公网可访问 ( 商城系统 进行商品订单信息的更改) 测试内网穿透
 * */
//http://ty2zwh.natappfree.cc/api/payment/alipay/callback/notify
        alipayTradePagePayRequest.setNotifyUrl(AliPayClientConfig.NOTIFY_PAYMENT_URL);
//同步跳转地址，仅支持http/https (返回给用户界面 支付成功/支付失败)
//        http://api.gmall.com/api/payment/alipay/callback/return
        alipayTradePagePayRequest.setReturnUrl(AliPayClientConfig.RETURN_PAYMENT_URL);
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
//支付金额，最小值0.01元(测试金额)
        bizContent.put("total_amount", 0.01);
//订单标题，不可使用特殊符号
        bizContent.put("subject", orderInfo.getTradeBody());
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

/******可选参数******/
        bizContent.put("timeout_express", "3m");  //超时时间为三分钟
//        bizContent.put("time_expire", "2016-12-31 10:05:01");  //超时时间 格式是一个日期类

        alipayTradePagePayRequest.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(alipayTradePagePayRequest);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

//        String body = response.getBody();//支付宝返回的支付宝字符串生成的页面
        return response.getBody();
    }
}
